window.onload = function() {
    var p = Player.getInstance(document.getElementById("player"));

    chrome.extension.onRequest.addListener(function(request, sender,
            sendResponse) {
        var response = {};
        switch (request.type) {
            case "load":
                p.load(request.urls);
                break;
            case "prev":
                p.prev();
                break;
            case "play":
                p.play();
                break;
            case "pause":
                p.pause();
                break;
            case "stop":
                p.stop();
                break;
            case "next":
                p.next();
                break;
            case "jump":
                p.jump(request.id);
                break;
            case "lock":
                p.lock();
                break;
            case "unlock":
                p.unlock();
                break;
            case "list":
                response = {
                    playlist: p.getPlaylist()
                };
                break;
            case "sort":
                p.sort(request.order);
                break;
            case "seek":
                p.seek(request.perc);
                break;
            default:
                break;
        }
        sendResponse(response);
    });

    chrome.extension.onConnect.addListener(function(port) {
        port.postMessage({
            type: "status",
            paused: p.isPaused(),
            track: p.getCurrent(),
            locked: p.isLocked(),
            duration: p.getDuration(),
            currentTime: p.getCurrentTime()
        });

        p.addEventListener("timeupdate", function(evt) {
            port.postMessage({
                type: "timeupdate",
                currentTime: this.currentTime,
                duration: this.duration
            });
        });

        p.addEventListener("loadstart", function(evt) {
            port.postMessage({
                type: "change",
                track: p.getCurrent()
            });
        });
    });
};